package com.zjdiepu.www.biz.zx;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.CreditQueryStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.AttachmentLabel;
import com.zjdiepu.www.base.enums.type.AttachmentSort;
import com.zjdiepu.www.base.enums.type.CodeType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.TypeData;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.StringUtil;
import com.zjdiepu.www.dao.base.OtherAttachmentsMapper;
import com.zjdiepu.www.dao.fk.FkAuditListMapper;
import com.zjdiepu.www.dao.other.OtherTaskAllocationMapper;
import com.zjdiepu.www.dao.system.BaseCustomerMapper;
import com.zjdiepu.www.dao.system.BaseSalersmanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessBuyerMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarAreaPriceMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarMapper;
import com.zjdiepu.www.dao.yw.YwBusinessLoanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.dao.zx.ZxCreditQueryMapper;
import com.zjdiepu.www.dao.zx.ZxQueryCreditApplyMapper;
import com.zjdiepu.www.dao.zx.ZxQueryCreditApplySubMapper;
import com.zjdiepu.www.ibiz.base.ISerialNumberService;
import com.zjdiepu.www.ibiz.third.IPhoneNumberAddrService;
import com.zjdiepu.www.ibiz.zpp.SystemService;
import com.zjdiepu.www.ibiz.zx.IZxCreditQueryService;
import com.zjdiepu.www.model.base.dto.OtherAttachments;
import com.zjdiepu.www.model.base.ext.OtherAttachmentsExt;
import com.zjdiepu.www.model.fk.dto.FkAuditList;
import com.zjdiepu.www.model.fk.ext.FkAuditListExt;
import com.zjdiepu.www.model.other.dto.OtherTaskAllocation;
import com.zjdiepu.www.model.other.ext.OtherTaskAllocationExt;
import com.zjdiepu.www.model.system.dto.BaseCustomer;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessBuyer;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessCarAreaPrice;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.ext.YwBusinessBuyerExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessCarAreaPriceExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessCarExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessLoanExt;
import com.zjdiepu.www.model.zx.dto.ZxCreditQuery;
import com.zjdiepu.www.model.zx.dto.ZxQueryCreditApply;
import com.zjdiepu.www.model.zx.dto.ZxQueryCreditApplySub;
import com.zjdiepu.www.model.zx.ext.ZxCreditQueryExt;
import com.zjdiepu.www.model.zx.ext.ZxQueryCreditApplySubExt;
import com.zjdiepu.www.model.zx.response.ZxCreditQueryDetail;
import com.zjdiepu.www.util.CommonUtil;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * zx_征信查询申请Service层操作实现<br/>
 * @author zhangpp<br/>
 * @time 2017年05月09日 15时16分<br/>
 * @since 1.0<br/>
 */
@Service
public class ZxCreditQueryServiceImpl extends BaseService implements IZxCreditQueryService {
	public static final Logger logger = LoggerFactory.getLogger(ZxCreditQueryServiceImpl.class);

	@Autowired
	private ZxCreditQueryMapper zxCreditQueryMapper;
	@Autowired
	private ZxQueryCreditApplySubMapper zxQueryCreditApplySubMapper;
	@Autowired
	private ZxQueryCreditApplyMapper zxQueryCreditApplyMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private YwBusinessBuyerMapper ywBusinessBuyerMapper;
	@Autowired
	private YwBusinessCarMapper ywBusinessCarMapper;
	@Autowired
	private YwBusinessLoanMapper ywBusinessLoanMapper;
	@Autowired
	private YwBusinessCarAreaPriceMapper ywBusinessCarAreaPriceMapper;
	@Autowired
	private OtherAttachmentsMapper otherAttachmentsMapper;
	@Autowired
	private BaseCustomerMapper baseCustomerMapper;
	@Autowired
	private ISerialNumberService serialNumberService;
	@Autowired
	private BaseSalersmanMapper baseSalersmanMapper;
	@Autowired
	private OtherTaskAllocationMapper otherTaskAllocationMapper;
	@Autowired
	private FkAuditListMapper fkAuditListMapper;
	@Autowired
	private SystemService systemService;
	@Resource
	private IPhoneNumberAddrService phoneNubmerAddrService;
	
	@Override
	public ZxCreditQuery checkAutoApplyedZxWithConfigDates(String customNo, String bankCode) {
		ZxQueryCreditApplySubExt zxQueryCreditApplySubExt = new ZxQueryCreditApplySubExt();
		zxQueryCreditApplySubExt.withOutPage();
		zxQueryCreditApplySubExt.setBaseWhere();
		zxQueryCreditApplySubExt.setCusNo(customNo); //结果表字段中身份证号不存在
		zxQueryCreditApplySubExt.setBankCode(bankCode);
		zxQueryCreditApplySubExt.setTypeData(TypeData.HZICBC.getCode());
		List<ZxQueryCreditApplySub> zxQueryCreditApplySubs = zxQueryCreditApplySubMapper.selectByExt(zxQueryCreditApplySubExt);
		if(CollectionUtils.isNotEmpty(zxQueryCreditApplySubs)) {
			ZxCreditQuery zxCreditQuery = new ZxCreditQuery();
			zxCreditQuery.setDpStatus(DpStatus.NORMAL.getCode());
			zxCreditQuery.setTypeData(TypeData.HZICBC.getCode());
			zxCreditQuery.setCreditQueryStatus(CreditQueryStatus.YI_CHA_XUN.getCode());
			zxCreditQuery.setBankCode(bankCode);
			zxCreditQuery.setOrderSql("`START_DATE` DESC");
			for(ZxQueryCreditApplySub zxQueryCreditApplySub : zxQueryCreditApplySubs) {
				zxCreditQuery.setQueryCreditApplySubId(zxQueryCreditApplySub.getId());
				ZxCreditQuery dbZxCreditQuery = zxCreditQueryMapper.selectRefined(zxCreditQuery);
				if(null != dbZxCreditQuery) {
					Date startDate = dbZxCreditQuery.getStartDate();
					if(null != startDate) {
						int countDiffDateDays = DateUtil.countDiffDays(new Date(), startDate);
						if(countDiffDateDays <= 30) {
							return dbZxCreditQuery;
						}
					}
				}
			}
		}
		return null;
	}
	
	@Override
	public ZxCreditQuery checkApplyedZxWithConfigDates(String customNo, String bankCode) {
		ZxQueryCreditApplySubExt zxQueryCreditApplySubExt = new ZxQueryCreditApplySubExt();
		zxQueryCreditApplySubExt.withOutPage();
		zxQueryCreditApplySubExt.setBaseWhere();
		zxQueryCreditApplySubExt.setCusNo(customNo); //结果表字段中身份证号不存在
		zxQueryCreditApplySubExt.setBankCode(bankCode);
		zxQueryCreditApplySubExt.setTypeData(TypeData.SYSTEM.getCode());
		List<ZxQueryCreditApplySub> zxQueryCreditApplySubs = zxQueryCreditApplySubMapper.selectByExt(zxQueryCreditApplySubExt);
		if(CollectionUtils.isNotEmpty(zxQueryCreditApplySubs)) {
			ZxCreditQuery zxCreditQuery = new ZxCreditQuery();
			zxCreditQuery.setDpStatus(DpStatus.NORMAL.getCode());
			zxCreditQuery.setTypeData(TypeData.SYSTEM.getCode());
			zxCreditQuery.setCreditQueryStatus(CreditQueryStatus.YI_CHA_XUN.getCode());
			zxCreditQuery.setBankCode(bankCode);
			zxCreditQuery.setOrderSql("`START_DATE` DESC");
			for(ZxQueryCreditApplySub zxQueryCreditApplySub : zxQueryCreditApplySubs) {
				zxCreditQuery.setQueryCreditApplySubId(zxQueryCreditApplySub.getId());
				ZxCreditQuery dbZxCreditQuery = zxCreditQueryMapper.selectRefined(zxCreditQuery);
				if(null != dbZxCreditQuery) {
					Date startDate = dbZxCreditQuery.getStartDate();
					if(null != startDate) {
						int countDiffDateDays = DateUtil.countDiffDays(new Date(), startDate);
						if(countDiffDateDays <= 30) {
							return dbZxCreditQuery;
						}
					}
				}
			}
		}
		return null;
	}
	
	@Override
	public boolean checkAutoApplyingZx(String customNo) {
		ZxQueryCreditApplySubExt zxQueryCreditApplySubExt = new ZxQueryCreditApplySubExt();
		zxQueryCreditApplySubExt.withOutPage();
		zxQueryCreditApplySubExt.setBaseWhere();
		zxQueryCreditApplySubExt.setCusNo(customNo); //结果表字段中身份证号不存在
		zxQueryCreditApplySubExt.setTypeData(TypeData.HZICBC.getCode());
		List<ZxQueryCreditApplySub> zxQueryCreditApplySubs = zxQueryCreditApplySubMapper.selectByExt(zxQueryCreditApplySubExt);
		if(CollectionUtils.isNotEmpty(zxQueryCreditApplySubs)) {
			ZxCreditQueryExt zxCreditQueryExt = new ZxCreditQueryExt();
			zxCreditQueryExt.setBaseWhere();
			zxCreditQueryExt.setTypeData(TypeData.HZICBC.getCode());
			zxCreditQueryExt.setCreditQueryStatus(CreditQueryStatus.DAI_CHA_XUN.getCode());
			for(ZxQueryCreditApplySub zxQueryCreditApplySub : zxQueryCreditApplySubs) {
				zxCreditQueryExt.setQueryCreditApplySubId(zxQueryCreditApplySub.getId());
				int count = zxCreditQueryMapper.countByExt(zxCreditQueryExt);
				if(count > 0) {
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public boolean checkApplyingZx(String customNo) {
		ZxQueryCreditApplySubExt zxQueryCreditApplySubExt = new ZxQueryCreditApplySubExt();
		zxQueryCreditApplySubExt.withOutPage();
		zxQueryCreditApplySubExt.setBaseWhere();
		zxQueryCreditApplySubExt.setCusNo(customNo); //结果表字段中身份证号不存在
		zxQueryCreditApplySubExt.setTypeData(TypeData.SYSTEM.getCode());
		List<ZxQueryCreditApplySub> zxQueryCreditApplySubs = zxQueryCreditApplySubMapper.selectByExt(zxQueryCreditApplySubExt);
		if(CollectionUtils.isNotEmpty(zxQueryCreditApplySubs)) {
			ZxCreditQueryExt zxCreditQueryExt = new ZxCreditQueryExt();
			zxCreditQueryExt.setBaseWhere();
			zxCreditQueryExt.setTypeData(TypeData.SYSTEM.getCode());
			zxCreditQueryExt.setCreditQueryStatus(CreditQueryStatus.DAI_CHA_XUN.getCode());
			for(ZxQueryCreditApplySub zxQueryCreditApplySub : zxQueryCreditApplySubs) {
				zxCreditQueryExt.setQueryCreditApplySubId(zxQueryCreditApplySub.getId());
				int count = zxCreditQueryMapper.countByExt(zxCreditQueryExt);
				if(count > 0) {
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public void saveChange(AbstractSysUser currentUser, String applyId, String busiId, String subApplyId) {
		String userId = currentUser.getId();
		String creatorName = currentUser.getName();
		
		//征信申请删除
		ZxQueryCreditApply oldZxQueryCreditApply = zxQueryCreditApplyMapper.selectByPrimaryKey(applyId);
		if(null == oldZxQueryCreditApply) {
			ExceptionHelper.thow("999", "该客户征信查询申请不存在");
		}
		
		//配偶征信子申请
		ZxQueryCreditApplySub oldPeiOuZxQueryCreditApplySub = zxQueryCreditApplySubMapper.selectByPrimaryKey(subApplyId);
		if(null == oldPeiOuZxQueryCreditApplySub) {
			ExceptionHelper.thow("999", "该客户征信查询子申请不存在");
		}
		
		Date now = new Date();
		DecimalFormat decimalFormat8 = new DecimalFormat("00000000");
		int nowTime = (int)(System.currentTimeMillis() / 1000);
		//新客户
		BaseCustomer newBaseCustomer = null;
		String newCustomerId = null;
		
		String peiOuCusNo = oldPeiOuZxQueryCreditApplySub.getCusNo();
		BaseCustomer baseCustomerParam = new BaseCustomer();
		baseCustomerParam.setCusNo(peiOuCusNo);
		baseCustomerParam.setDpStatus(DpStatus.NORMAL.getCode());
		BaseCustomer oldBaseCustomer = baseCustomerMapper.selectRefined(baseCustomerParam);
		if(null == oldBaseCustomer) { //客户不存在，需要新增
			newBaseCustomer = new BaseCustomer();
			newBaseCustomer.initInsertData(userId, creatorName);
			String cusCode = "C" + DateUtil.dateToFormat(now, "yyyyMMdd") + new DecimalFormat("0000").format(serialNumberService.createSerialNumber(CodeType.CUSTOMER,null, false));
			newBaseCustomer.setCusCode(cusCode);
			newBaseCustomer.setName(oldPeiOuZxQueryCreditApplySub.getCusName());
			newBaseCustomer.setCusNo(oldPeiOuZxQueryCreditApplySub.getCusNo());
			newBaseCustomer.setCusNo2(StringUtil.subWithNHeadMTail(oldPeiOuZxQueryCreditApplySub.getCusNo(), 5, 4, "*"));
			
			String salersmanIdThen = oldZxQueryCreditApply.getSalersmanIdThen();
			newBaseCustomer.setSalesmanId(salersmanIdThen); 
			BaseSalersman baseSalersman = baseSalersmanMapper.selectByPrimaryKey(salersmanIdThen);
			if(null != baseSalersman) {
				newBaseCustomer.setSalesmanName(baseSalersman.getName());
				newBaseCustomer.setSalesmanCode(baseSalersman.getSalersmanCode());
			}
			
			newCustomerId = newBaseCustomer.getId();
			baseCustomerMapper.insert(newBaseCustomer); //新客户
		} else {
			newBaseCustomer = oldBaseCustomer;
			newCustomerId = newBaseCustomer.getId();
		}
		
		//申请
		ZxQueryCreditApply newZxQueryCreditApply = new ZxQueryCreditApply();
		BeanUtils.copyProperties(oldZxQueryCreditApply, newZxQueryCreditApply);
		newZxQueryCreditApply.initInsertData(userId, creatorName);
		String queryCreditApplyCode = "ZXCXSQ" +  DateUtil.dateTo8Str(now) + decimalFormat8.format(serialNumberService.createSerialNumber(CodeType.CREDIT_APPLY, null, true));
		newZxQueryCreditApply.setQueryCreditApplyCode(queryCreditApplyCode);
		
		//征信结果
		ZxCreditQueryExt zxCreditQueryExt = new ZxCreditQueryExt();
		zxCreditQueryExt.notDeleted();
		zxCreditQueryExt.withOutPage();
		zxCreditQueryExt.setQueryCreditApplyId(applyId);
		List<ZxCreditQuery> oldZxCreditQuerys = zxCreditQueryMapper.selectByExt(zxCreditQueryExt);
		List<ZxCreditQuery> newZxCreditQuerys = CollectionInitUtil.emptyList();
		ZxCreditQuery newZhuJieRenCreditQuery = null;
		
		//子申请
		ZxQueryCreditApplySubExt zxQueryCreditApplySubExt = new ZxQueryCreditApplySubExt();
		zxQueryCreditApplySubExt.notDeleted();
		zxQueryCreditApplySubExt.withOutPage();
		zxQueryCreditApplySubExt.setQueryCreditApplyId(applyId);
		List<ZxQueryCreditApplySub> oldZxQueryCreditApplySubs = zxQueryCreditApplySubMapper.selectByExt(zxQueryCreditApplySubExt);
		List<ZxQueryCreditApplySub> newZxQueryCreditApplySubs = CollectionInitUtil.emptyList();
		
		OtherTaskAllocationExt otherTaskAllocationExt = new OtherTaskAllocationExt(); //分配更换
		otherTaskAllocationExt.notDeleted();
		otherTaskAllocationExt.withOutPage();
		otherTaskAllocationExt.setModeId("ZXCXSQ");
		otherTaskAllocationExt.setRows(1);
		List<OtherTaskAllocation> newOtherTaskAllocations = CollectionInitUtil.emptyList();
		List<String> oldOtherTaskAllocationIds = CollectionInitUtil.emptyList();
		ZxQueryCreditApplySub newZhuJieRenSubApply = null;
		for(ZxQueryCreditApplySub oldZxQueryCreditApplySub : oldZxQueryCreditApplySubs) {
			ZxQueryCreditApplySub newZxQueryCreditApplySub = new ZxQueryCreditApplySub();
			BeanUtils.copyProperties(oldZxQueryCreditApplySub, newZxQueryCreditApplySub);
			newZxQueryCreditApplySub.initInsertData(userId, creatorName);
			
			otherTaskAllocationExt.setDataid(oldZxQueryCreditApplySub.getId());
			List<OtherTaskAllocation> oldOtherTaskAllocations = otherTaskAllocationMapper.selectByExt(otherTaskAllocationExt);
			if(CollectionUtils.isNotEmpty(oldOtherTaskAllocations)) {
				OtherTaskAllocation oldOtherTaskAllocation = oldOtherTaskAllocations.get(0);
				OtherTaskAllocation newOtherTaskAllocation = new OtherTaskAllocation();
				BeanUtils.copyProperties(oldOtherTaskAllocation, newOtherTaskAllocation);
				
				newOtherTaskAllocation.initInsertData(userId, creatorName);
				newOtherTaskAllocation.setDataid(newZxQueryCreditApplySub.getId());
				newOtherTaskAllocations.add(newOtherTaskAllocation);
				oldOtherTaskAllocationIds.add(oldOtherTaskAllocation.getId());
			}
			
			newZxQueryCreditApplySub.setQueryCreditApplyId(newZxQueryCreditApply.getId());
			newZxQueryCreditApplySub.setOldId(oldZxQueryCreditApplySub.getId());
			if("01".equals(newZxQueryCreditApplySub.getCreditPeopleType())){ //配偶
				newZxQueryCreditApplySub.setCreditPeopleType("03");
				newZhuJieRenSubApply = newZxQueryCreditApplySub;//新主借人
			} else if("03".equals(newZxQueryCreditApplySub.getCreditPeopleType())) { //主借人
				newZxQueryCreditApplySub.setCreditPeopleType("01");
			}
			
			for(ZxCreditQuery oldZxCreditQuery : oldZxCreditQuerys) {
				if(oldZxCreditQuery.getQueryCreditApplySubId().equals(oldZxQueryCreditApplySub.getId())) {
					ZxCreditQuery newZxCreditQuery = new ZxCreditQuery();
					BeanUtils.copyProperties(oldZxCreditQuery, newZxCreditQuery);
					
					newZxCreditQuery.initInsertData(userId, creatorName);
					newZxCreditQuery.setQueryCreditApplyId(newZxQueryCreditApply.getId());
					newZxCreditQuery.setQueryCreditApplySubId(newZxQueryCreditApplySub.getId());
					String creditQueryCode = "ZXCX" +  DateUtil.dateToFormat(now, "yyyyMMdd") + decimalFormat8.format(serialNumberService.createSerialNumber(CodeType.CREDIT_QUERY, null, true));
					newZxCreditQuery.setCreditQueryCode(creditQueryCode);
					newZxCreditQuery.setCustomerId(newCustomerId);
					if("01".equals(newZxCreditQuery.getCreditPeopleType())){ //配偶
						newZxCreditQuery.setCreditPeopleType("03");
						newZhuJieRenCreditQuery = newZxCreditQuery;//新主借人
					} else if("03".equals(newZxCreditQuery.getCreditPeopleType())) { //主借人
						newZxCreditQuery.setCreditPeopleType("01");
					}
					newZxCreditQuerys.add(newZxCreditQuery);
					break;
				}
			}
			newZxQueryCreditApplySubs.add(newZxQueryCreditApplySub);
		}
		
		if(null == newZhuJieRenSubApply) {
			ExceptionHelper.thow("999", "配偶征信子申请记录丢失");
		}
		
		if(null == newZhuJieRenCreditQuery) {
			ExceptionHelper.thow("999", "配偶征信查询结果记录丢失");
		}
		
		if(CollectionUtils.isNotEmpty(newOtherTaskAllocations)) {
			otherTaskAllocationMapper.insertBatch(newOtherTaskAllocations);
		}
		
		if(CollectionUtils.isNotEmpty(oldOtherTaskAllocationIds)) {
//			@update 2017-11-30 不删老数据，只是置为弃贷状态busiStatus:9820
//			otherTaskAllocationMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldOtherTaskAllocationIds);
		}
		
		if(CollectionUtils.isNotEmpty(newZxQueryCreditApplySubs)) {
			zxCreditQueryMapper.insertBatch(newZxCreditQuerys);
		}
		
		List<String> oldCreditQueryIds = oldZxCreditQuerys.stream().map(item -> item.getId()).collect(Collectors.toList());
		if(CollectionUtils.isNotEmpty(oldCreditQueryIds)) {
//			@update 2017-11-30 不删老数据，只是置为弃贷状态busiStatus:9820
//			zxCreditQueryMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldCreditQueryIds);
		}
		
		//征信附件
		OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
		otherAttachmentsExt.setDataid(applyId);
		otherAttachmentsExt.withOutPage();
		otherAttachmentsExt.setBaseWhere();
		List<OtherAttachments> oldOtherAttachmentses = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
		List<OtherAttachments> newOtherAttachmentses = CollectionInitUtil.emptyList();
		for(OtherAttachments oldOtherAttachments : oldOtherAttachmentses) {
			OtherAttachments newOtherAttachments = new OtherAttachments();
			BeanUtils.copyProperties(oldOtherAttachments, newOtherAttachments);
			
			newOtherAttachments.initInsertData(userId, creatorName);
			newOtherAttachments.setDataid(newZxQueryCreditApply.getId());
			newOtherAttachments.setCustomerId(newCustomerId);
			//寻找dataid
			for(ZxQueryCreditApplySub newZxQueryCreditApplySub : newZxQueryCreditApplySubs) {
				if(newZxQueryCreditApplySub.getOldId().equals(oldOtherAttachments.getDataid())) {
					newOtherAttachments.setSubDataid(newZxQueryCreditApplySub.getId());
					break;
				}
			}
			
			//交换标签
			if(AttachmentSort.SHEN_FEN_ZHENG_MING.getCode().equals(newOtherAttachments.getAttachmentSort())){ //主借人
				newOtherAttachments.setAttachmentSort(AttachmentSort.PEI_OU_SHEN_FEN_ZHENG_MING.getCode());
				if(AttachmentLabel.SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode());
				} else if(AttachmentLabel.SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode());
				} else if(AttachmentLabel.ZHUJIEREN_ZHENG_XIN_SHOU_QUAN_SHU.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.PEIOU_ZHENG_XIN_SHOU_QUAN_SHU.getCode());
				} else if(AttachmentLabel.ZHUJIEREN_ZHENG_XIN_QIANZIZHAO.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.PEIOU_ZHENG_XIN_QIANZIZHAO.getCode());
				}
			} else if(AttachmentSort.PEI_OU_SHEN_FEN_ZHENG_MING.getCode().equals(newOtherAttachments.getAttachmentSort())) { //主借人
				newOtherAttachments.setAttachmentSort(AttachmentSort.SHEN_FEN_ZHENG_MING.getCode());
				if(AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode());
				} else if(AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode());
				} else if(AttachmentLabel.PEIOU_ZHENG_XIN_SHOU_QUAN_SHU.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.ZHUJIEREN_ZHENG_XIN_SHOU_QUAN_SHU.getCode());
				} else if(AttachmentLabel.PEIOU_ZHENG_XIN_QIANZIZHAO.getCode().equals(newOtherAttachments.getFileLabel())) {
					newOtherAttachments.setFileLabel(AttachmentLabel.ZHUJIEREN_ZHENG_XIN_QIANZIZHAO.getCode());
				}
			}
			newOtherAttachmentses.add(newOtherAttachments);
		}
		
		if(CollectionUtils.isNotEmpty(newOtherAttachmentses)) {
			otherAttachmentsMapper.insertBatch(newOtherAttachmentses);
		}
		
		List<String> oldOtherAttachmentsIds = oldOtherAttachmentses.stream().map(item -> item.getId()).collect(Collectors.toList());
		if(CollectionUtils.isNotEmpty(oldOtherAttachmentsIds)) {
//			@update 2017-11-30 不删老数据，只是置为弃贷状态busiStatus:9820
//			otherAttachmentsMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldOtherAttachmentsIds);
		}
				
		newZxQueryCreditApply.setCustomerId(newCustomerId); //可能为空，也可能已经产生数据
		newZxQueryCreditApply.setCustomerName(newZhuJieRenSubApply.getCusName());
		newZxQueryCreditApply.setCustomerNo(newZhuJieRenSubApply.getCusNo());
		newZxQueryCreditApply.setCustomerNo2(newZhuJieRenSubApply.getCusNo2());
		zxQueryCreditApplyMapper.insert(newZxQueryCreditApply);
		zxQueryCreditApplyMapper.deleteByPrimaryKey(applyId);
		
		if(CollectionUtils.isNotEmpty(newZxQueryCreditApplySubs)) {
			zxQueryCreditApplySubMapper.insertBatch(newZxQueryCreditApplySubs);
		}
		
		List<String> oldApplySubIds = oldZxQueryCreditApplySubs.stream().map(item -> item.getId()).collect(Collectors.toList());
		if(CollectionUtils.isNotEmpty(oldApplySubIds)) {
//			@update 2017-11-30 不删老数据，只是置为弃贷状态busiStatus:9820
//			zxQueryCreditApplySubMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldApplySubIds);
		}
		
//		=============================征信相关结束==============================
		
//		=============================业务相关开始==============================		
		//业务表
		YwBusiness newYwBusiness = new YwBusiness();
		newYwBusiness.initInsertData(userId, creatorName);
		String busiCode = DateUtil.dateToFormat(now, "yyyyMMdd") + new DecimalFormat("00000000").format(serialNumberService.createSerialNumber(CodeType.BUSINESS, null, true));
		
		newYwBusiness.setBusiCode(busiCode);
		newYwBusiness.setQueryCreditApplyId(newZxQueryCreditApply.getId());    //征信申请主键
		newYwBusiness.setCreditQueryId(newZhuJieRenCreditQuery.getId());  //征信结果主键
		newYwBusiness.setDealerId(oldZxQueryCreditApply.getDealerId());
		newYwBusiness.setCustomerId(newBaseCustomer.getId());
		newYwBusiness.setCustomerName(newBaseCustomer.getName());
		newYwBusiness.setCustomerNo(newBaseCustomer.getCusNo());
		
		//料登记10
		newYwBusiness.setBusiStatus(10);  
		//业务电审状态10
		newYwBusiness.setPhoneStatus(10); 
		//通道状态无
		newYwBusiness.setChannelStatus(10);
		//通融状态通融
		newYwBusiness.setTongrongStatus(10);
		//额外状态1未定级
		newYwBusiness.setAddedStatus1(10);
		//欠资料状态
		newYwBusiness.setLessInformationStatus(20);  
		//归档状态为
		newYwBusiness.setStatusArchive(10);
		//所处银行
		newYwBusiness.setBankLoan(newZxQueryCreditApply.getBankCode());
		//征信录入时间
		newYwBusiness.setOperatorDate(newZhuJieRenCreditQuery.getOperatorDate());
		newYwBusiness.setSubmitTime(now);
		if(StringUtils.isNotBlank(busiId)) {
			YwBusiness oldYwBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
			if(null != oldYwBusiness) { //保留字段
				newYwBusiness.setRealLoanAmount(oldYwBusiness.getRealLoanAmount());
				newYwBusiness.setSignLoanAmount(oldYwBusiness.getSignLoanAmount());
				
				//使用真实的业务员，与申请时有点
				newYwBusiness.setSalesmanId(oldYwBusiness.getSalesmanId());
				newYwBusiness.setSalesmanCode(oldYwBusiness.getSalesmanCode());
			}
		}
		if(StringUtils.isBlank(newYwBusiness.getSalesmanId())) { //没有业务员赋值时，使用申请的经办业务员
			String salersmanIdThen = newZxQueryCreditApply.getSalersmanIdThen();
			if(StringUtils.isNotBlank(salersmanIdThen)) {
				newYwBusiness.setSalesmanId(salersmanIdThen); //老记录申请时选择的业务员
				BaseSalersman salersmanThen = baseSalersmanMapper.selectByPrimaryKey(salersmanIdThen);
				if(null != salersmanThen) {
					newYwBusiness.setSalesmanCode(salersmanThen.getSalersmanCode());
				}
			}
		}
		ywBusinessMapper.insert(newYwBusiness);
		
		if(StringUtils.isNotBlank(busiId)) { //老业务
			YwBusiness ywBusiness = new YwBusiness();
			ywBusiness.setId(busiId);
			ywBusiness.setBusiStatus(BusiStatus.QI_DAI.getCode());
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
//			@update 2017-11-30 除了待审核列表，不删老数据，只是置为弃贷状态busiStatus:9820
//			ywBusinessMapper.updateBatch(StringUtil.createNCharStr(8, "0000"), "换主借人", nowTime, DpStatus.DELETED.getCode(), Arrays.asList(new String[]{busiId}));
			FkAuditListExt fkAuditList = new FkAuditListExt();
			fkAuditList.setBusiId(busiId);
			fkAuditList.withOutPage();
			List<FkAuditList> fkAuditLists = fkAuditListMapper.selectByExt(fkAuditList);
			List<String> oldfkAuditListIds = fkAuditLists.stream().map(item -> item.getId()).collect(Collectors.toList());
			if(CollectionUtils.isNotEmpty(oldfkAuditListIds)) {
//				@update 2017-11-30 除了待审核列表，不删老数据，只是置为弃贷状态busiStatus:9820
				fkAuditListMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldfkAuditListIds);
			}
			//购车人
			YwBusinessBuyerExt ywBusinessBuyerExt = new YwBusinessBuyerExt();
			ywBusinessBuyerExt.notDeleted();
			ywBusinessBuyerExt.withOutPage();
			ywBusinessBuyerExt.setBusiId(busiId);
			List<YwBusinessBuyer> oldYwBusinessBuyers = ywBusinessBuyerMapper.selectByExt(ywBusinessBuyerExt);
			List<YwBusinessBuyer> newYwBusinessBuyers = CollectionInitUtil.emptyList();
			
			for(YwBusinessBuyer oldYwBusinessBuyer : oldYwBusinessBuyers) {
				YwBusinessBuyer newYwBusinessBuyer = new YwBusinessBuyer();
				BeanUtils.copyProperties(oldYwBusinessBuyer, newYwBusinessBuyer);
				
				newYwBusinessBuyer.initInsertData(userId, creatorName);
				newYwBusinessBuyer.setBusiId(newYwBusiness.getId());
				newYwBusinessBuyer.setCusId(newBaseCustomer.getId());
				
				if("01".equals(newYwBusinessBuyer.getCarManType())) {
					newYwBusinessBuyer.setCarManType("03");
				} else if("03".equals(newYwBusinessBuyer.getCarManType())) {
					newYwBusinessBuyer.setCarManType("01");
				}
				newYwBusinessBuyers.add(newYwBusinessBuyer);
			}
			
			if(CollectionUtils.isNotEmpty(newYwBusinessBuyers)) {
				ywBusinessBuyerMapper.insertBatch(newYwBusinessBuyers);
			}
			
			List<String> oldYwBusinessBuyerIds = oldYwBusinessBuyers.stream().map(item -> item.getId()).collect(Collectors.toList());
			if(CollectionUtils.isNotEmpty(oldYwBusinessBuyerIds)) {
//				@update 2017-11-30 除了待审核列表，不删老数据，只是置为弃贷状态busiStatus:9820
//				ywBusinessBuyerMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldYwBusinessBuyerIds);
			}
			
			//车辆信息
			YwBusinessCarExt ywBusinessCarExt = new YwBusinessCarExt();
			ywBusinessCarExt.notDeleted();
			ywBusinessCarExt.setBusiId(busiId);
			ywBusinessCarExt.setRows(1);
			YwBusinessCar newYwBusinessCar = null;
			List<YwBusinessCar> oldYwBusinessCars = ywBusinessCarMapper.selectByExt(ywBusinessCarExt);
			if(CollectionUtils.isNotEmpty(oldYwBusinessCars)) {
				YwBusinessCar oldYwBusinessCar = oldYwBusinessCars.get(0);
				newYwBusinessCar = new YwBusinessCar();
				BeanUtils.copyProperties(oldYwBusinessCar, newYwBusinessCar);
				newYwBusinessCar.initInsertData(userId, creatorName);
				newYwBusinessCar.setBusiId(newYwBusiness.getId());
				newYwBusinessCar.setCusId(newBaseCustomer.getId());
				ywBusinessCarMapper.insert(newYwBusinessCar);
//				@update 2017-11-30 除了待审核列表，不删老数据，只是置为弃贷状态busiStatus:9820
//				ywBusinessCarMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), Arrays.asList(new String[]{oldYwBusinessCar.getId()}));
			}
			
			if(null != newYwBusinessCar) {
				//车贷信息
				YwBusinessLoanExt ywBusinessLoanExt = new YwBusinessLoanExt();
				ywBusinessLoanExt.notDeleted();
				ywBusinessLoanExt.setBusiId(busiId);
				ywBusinessLoanExt.setRows(1);
				List<YwBusinessLoan> oldYwBusinessLoans = ywBusinessLoanMapper.selectByExt(ywBusinessLoanExt);
				if(CollectionUtils.isNotEmpty(oldYwBusinessLoans)) {
					YwBusinessLoan oldYwBusinessLoan = oldYwBusinessLoans.get(0);
					YwBusinessLoan newYwBusinessLoan = new YwBusinessLoan();
					BeanUtils.copyProperties(oldYwBusinessLoan, newYwBusinessLoan);
					newYwBusinessLoan.initInsertData(userId, creatorName);
					newYwBusinessLoan.setBusiId(newYwBusiness.getId());
					newYwBusinessLoan.setCusId(newBaseCustomer.getId());
					newYwBusinessLoan.setCarId(newYwBusinessCar.getId());
					ywBusinessLoanMapper.insert(newYwBusinessLoan);
//					@update 2017-11-30 除了待审核列表，不删老数据，只是置为弃贷状态busiStatus:9820
//					ywBusinessLoanMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), Arrays.asList(new String[]{oldYwBusinessLoan.getId()}));
				}
				//估价信息
				YwBusinessCarAreaPriceExt ywBusinessCarAreaPriceExt = new YwBusinessCarAreaPriceExt();
				ywBusinessCarAreaPriceExt.notDeleted();
				ywBusinessCarAreaPriceExt.withOutPage();
				ywBusinessCarAreaPriceExt.setBusiId(busiId);
				List<YwBusinessCarAreaPrice> oldYwBusinessCarAreaPrices = ywBusinessCarAreaPriceMapper.selectByExt(ywBusinessCarAreaPriceExt);
				List<YwBusinessCarAreaPrice> newYwBusinessCarAreaPrices = CollectionInitUtil.emptyList();
				
				for(YwBusinessCarAreaPrice oldYwBusinessCarAreaPrice : oldYwBusinessCarAreaPrices) {
					YwBusinessCarAreaPrice newYwBusinessCarAreaPrice = new YwBusinessCarAreaPrice();
					BeanUtils.copyProperties(oldYwBusinessCarAreaPrice, newYwBusinessCarAreaPrice);
					
					newYwBusinessCarAreaPrice.initInsertData(userId, creatorName);
					newYwBusinessCarAreaPrice.setBusiId(newYwBusiness.getId());
					newYwBusinessCarAreaPrice.setCarId(newYwBusinessCar.getId());
					newYwBusinessCarAreaPrices.add(newYwBusinessCarAreaPrice);
				}
				
				if(CollectionUtils.isNotEmpty(newYwBusinessCarAreaPrices)) {
					ywBusinessCarAreaPriceMapper.insertBatch(newYwBusinessCarAreaPrices);
				}
				
				List<String> oldYwBusinessCarAreaPriceIds = oldYwBusinessCarAreaPrices.stream().map(item -> item.getId()).collect(Collectors.toList());
				if(CollectionUtils.isNotEmpty(oldYwBusinessCarAreaPriceIds)) {
//					@update 2017-11-30 除了待审核列表，不删老数据，只是置为弃贷状态busiStatus:9820
//					ywBusinessCarAreaPriceMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldYwBusinessCarAreaPriceIds);
				}
			}
			
			//业务附件
			OtherAttachmentsExt otherAttachmentsExtYw = new OtherAttachmentsExt();
			otherAttachmentsExtYw.setDataid(busiId);
			otherAttachmentsExtYw.withOutPage();
			otherAttachmentsExtYw.setBaseWhere();
			List<OtherAttachments> oldOtherAttachmentsYws = otherAttachmentsMapper.selectByExt(otherAttachmentsExtYw);
			
			List<String> oldoldOtherAttachmentsYwIds = oldOtherAttachmentsYws.stream().map(item -> item.getId()).collect(Collectors.toList());
			if(CollectionUtils.isNotEmpty(oldoldOtherAttachmentsYwIds)) {
//				@update 2017-11-30 除了待审核列表，不删老数据，只是置为弃贷状态busiStatus:9820
//				otherAttachmentsMapper.updateBatch(userId, creatorName, nowTime, DpStatus.DELETED.getCode(), oldoldOtherAttachmentsYwIds);
			}
		} else { //新业务
			if(null == newZhuJieRenCreditQuery.getCreditResult() || "03".equals(newZhuJieRenCreditQuery.getCreditResult())) {
				return;
			}
			
			List<YwBusinessBuyer> newYwBusinessBuyers = CollectionInitUtil.emptyList();
			for(ZxQueryCreditApplySub newZxQueryCreditApplySub : newZxQueryCreditApplySubs) {
				String creditPeopleType = newZxQueryCreditApplySub.getCreditPeopleType();
				String cusName = newZxQueryCreditApplySub.getCusName();
				String cusNo = newZxQueryCreditApplySub.getCusNo();
				
				//添加yw_business_buyer表
				YwBusinessBuyer ywBusinessBuyer = new YwBusinessBuyer();
				ywBusinessBuyer.initInsertData(userId, creatorName); 
				ywBusinessBuyer.setCarManType(creditPeopleType);
				ywBusinessBuyer.setBusiId(newYwBusiness.getId());
				ywBusinessBuyer.setCusId(newBaseCustomer.getId());
				ywBusinessBuyer.setName(cusName);
				ywBusinessBuyer.setIdno(cusNo);
				ywBusinessBuyer.setIdno2(newZxQueryCreditApplySub.getCusNo2());
				//获取户籍信息
				try {
					Map<String, Object> jsonMaps = phoneNubmerAddrService.getIdCordInfo(cusNo);
					if(MapUtils.isNotEmpty(jsonMaps)) {
						JSONObject json = CommonUtil.getJSONObject(jsonMaps.get("result"));    
						int isok = json.getInt("isok");
						if(isok != -1) {
							ywBusinessBuyer.setArea(String.valueOf(json.get("area")));
							ywBusinessBuyer.setSex("男".equals(json.getString("sex")) ? "01" : "02");
							ywBusinessBuyer.setFamilyRegister(String.valueOf(json.get("province")));
						} else {
							ExceptionHelper.thow("999", "获取户籍信息失败");
						}
					}
				} catch (Exception e) {
					ExceptionHelper.thow("999", "获取户籍信息异常");
				}
				newYwBusinessBuyers.add(ywBusinessBuyer);
			}
			ywBusinessBuyerMapper.insertBatch(newYwBusinessBuyers);
		}
		
		systemService.diepuNewsHandle(currentUser, ModeIDType.BGZJR.getCode(), "32", busiId, null, newZxQueryCreditApply.getCustomerName(), oldZxQueryCreditApply.getCustomerName());
		 
		
	}
	
	@Override
	public List<ZxCreditQuery> selectForChange(ZxCreditQueryExt zxCreditQueryExt) {
		return zxCreditQueryMapper.selectForChange(zxCreditQueryExt);
	}
	
	@Override
	public int countForChange(ZxCreditQueryExt zxCreditQueryExt) {
		return zxCreditQueryMapper.countForChange(zxCreditQueryExt);
	}
	
	@Override
	public void saveUpdateAndDelete(ZxCreditQuery zxCreditQuery, OperateType operType) {
		switch (operType) {
		case add:
			zxCreditQuery.initInsertData(zxCreditQuery.getModifier(), zxCreditQuery.getModifierName());
			zxCreditQueryMapper.insert(zxCreditQuery);
			break;
		case edit:
			zxCreditQuery.initUpdateData(zxCreditQuery.getModifier(), zxCreditQuery.getModifierName());
			// 影响的记录数
			int updateCount = zxCreditQueryMapper.updateByPrimaryKeySelective(zxCreditQuery);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			zxCreditQuery.initDeleteData(zxCreditQuery.getModifier(), zxCreditQuery.getModifierName());
			// 影响的记录数
			int deleteCount = zxCreditQueryMapper.updateByPrimaryKeySelective(zxCreditQuery);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<ZxCreditQuery> selectByExt(ZxCreditQueryExt zxCreditQueryExt) {
		return zxCreditQueryMapper.selectByExt(zxCreditQueryExt);
	}
	
	@Override
	public int countByExt(ZxCreditQueryExt zxCreditQueryExt){
		return zxCreditQueryMapper.countByExt(zxCreditQueryExt);
	}
	
	@Override
	public ZxCreditQuery selectById(String id) {
		return zxCreditQueryMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			zxCreditQueryMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(ZxCreditQuery zxCreditQuery) {
		return zxCreditQueryMapper.countRefined(zxCreditQuery);
	}

	@Override
	public ZxCreditQuery selectRefined(ZxCreditQuery zxCreditQuery) {
		return zxCreditQueryMapper.selectRefined(zxCreditQuery);
	}
	
	@Override
	public int deletedRefined(ZxCreditQuery zxCreditQuery) {
		return zxCreditQueryMapper.deletedRefined(zxCreditQuery);
	}

	@Override
	public boolean repeat(ZxCreditQuery zxCreditQuery) {
		int count = countRefined(zxCreditQuery);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(zxCreditQuery.getId())) {
			return true;
		}
		ZxCreditQuery dbItem = selectRefined(zxCreditQuery);
		if(null == dbItem) {
			return false;
		}
		return !zxCreditQuery.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return zxCreditQueryMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<ZxCreditQuery> zxCreditQuerys) {
		return zxCreditQueryMapper.insertBatch(zxCreditQuerys);
	}
	
	@Override
	public List<ZxCreditQueryDetail> selectMultiByApplyId(String applyId) {
		return zxCreditQueryMapper.selectMultiByApplyId(applyId);
	}
}
